package com.pe.regope.seguridad;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.userdetails.UserDetails;

import com.pe.regope.negocio.service.UserManagerService;

public class REGOPEAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
	@Resource
	private UserManagerService userDetailsService;

	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
	}
	
	@Override
	protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		UserDetails loadedUser;

		try {
			loadedUser = this.getUserDetailsService().getUser(username,authentication.getCredentials().toString());
		}catch (DataAccessException repositoryProblem) {
			throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
		}

		if (loadedUser == null) {
			throw new AuthenticationServiceException(
					"UserDetailsService returned null, which is an interface contract violation");
		}
		return loadedUser;
	}
	
	public UserManagerService getUserDetailsService() {
		return userDetailsService;
	}
	
	public void setUserDetailsService(UserManagerService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}	
}
